{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "2ae1bda5-a88c-4e8b-9ac4-6a639a3aa82a",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sparkai.llm.llm import ChatSparkLLM, ChunkPrintHandler\n",
    "from sparkai.core.messages import ChatMessage"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "32047c9a-83b4-4176-aa36-1e1e96b16d92",
   "metadata": {},
   "outputs": [],
   "source": [
    "#配置\n",
    "SPARKAI_URL = 'wss://spark-api.xf-yun.com/v1.1/chat'\n",
    "SPARKAI_APP_ID = 'xxxxxxxx'\n",
    "SPARKAI_API_SECRET = 'xxxxxxxx'\n",
    "SPARKAI_API_KEY = 'xxxxxxxx'\n",
    "SPARKAI_DOMAIN = 'lite'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "deaa54b6-ae31-4a51-bd1e-3001858c4a88",
   "metadata": {},
   "outputs": [],
   "source": [
    "#将llm封装成接口进行调用\n",
    "def ask_spark_ai(question):\n",
    "    spark = ChatSparkLLM(\n",
    "        spark_api_url=SPARKAI_URL,\n",
    "        spark_app_id=SPARKAI_APP_ID,\n",
    "        spark_api_key=SPARKAI_API_KEY,\n",
    "        spark_api_secret=SPARKAI_API_SECRET,\n",
    "        spark_llm_domain=SPARKAI_DOMAIN,\n",
    "        streaming=False,\n",
    "    )\n",
    "    messages = [ChatMessage(role=\"user\", content=question)]\n",
    "    handler = ChunkPrintHandler()\n",
    "    response = spark.generate([messages], callbacks=[handler])\n",
    "    return response.generations[0][0].text"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "5f26c10c-78bc-44cf-9f18-07ffa02e04a6",
   "metadata": {},
   "outputs": [],
   "source": [
    "#API库\n",
    "#Perception Function\n",
    "def get_drone_position(): pass #Return the current location of the drone [X, Y, Z].\n",
    "def detect_object(object_type): pass #Identify the specified object type (e.g., obstacle, target) and return its coordinates [X, Y, Z].\n",
    "def get_battery_status(): pass#Return the current battery level percentage.\n",
    "\n",
    "#Action Function\n",
    "def takeoff(): pass#Command the drone to take off to a specified altitude. Return nothing.\n",
    "def land(): pass#Command the drone to safely land at the current or specified location. Return nothing.\n",
    "def fly_to(destination): pass#Fly the drone to the specified destination [X, Y, Z] coordinates. Return nothing.\n",
    "def hover(duration): pass#Hold the drone at its current position for the specified duration. Return nothing.\n",
    "def start_recording(): pass#Begin video recording with the onboard camera. Return nothing.\n",
    "def stop_recording(): pass#Stop video recording. Return the saved video file path or identifier.\n",
    "def capture_image(): pass#Capture a high-resolution image at the current location. Return the image file path or identifier.\n",
    "def check_gps_signal(): pass#Check the current GPS signal strength and status. Return signal quality indicator.\n",
    "def emergency_stop(): pass#Immediately stop all drone movements and hover in place. Return nothing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "9c556863-b57b-4ace-9f37-9f41fec3493e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Enter answer:  我现在想模拟无人机的操作，请帮我以下面我所声明的函数和后面的说明，实现一下它们，然后调用你所实现的方法，对无人机进行操作无人机起飞前，检查一下电池的状态，然后起飞，向上飞10，向左飞20，然后检查一下gps的状态，最后进行着陆：#Perception Function def get_drone_position(): pass #Return the current location of the drone [X, Y, Z]. def detect_object(object_type): pass #Identify the specified object type (e.g., obstacle, target) and return its coordinates [X, Y, Z]. def get_battery_status(): pass#Return the current battery level percentage.  #Action Function def takeoff(): pass#Command the drone to take off to a specified altitude. Return nothing. def land(): pass#Command the drone to safely land at the current or specified location. Return nothing. def fly_to(destination): pass#Fly the drone to the specified destination [X, Y, Z] coordinates. Return nothing. def hover(duration): pass#Hold the drone at its current position for the specified duration. Return nothing. def start_recording(): pass#Begin video recording with the onboard camera. Return nothing. def stop_recording(): pass#Stop video recording. Return the saved video file path or identifier. def capture_image(): pass#Capture a high-resolution image at the current location. Return the image file path or identifier. def check_gps_signal(): pass#Check the current GPS signal strength and status. Return signal quality indicator. def emergency_stop(): pass#Immediately stop all drone movements and hover in place. Return nothing.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-10-31 21:40:10 中国标准时间 - SparkPythonSDK - ERROR - [D:\\Python\\Python312\\Lib\\site-packages\\sparkai\\llm\\llm.py:694] - SparkLLMClient wait LLM api response timeout 30 seconds\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Executing Code: ```python\n",
      "import time\n",
      "\n",
      "class Drone:\n",
      "    def __init__(self):\n",
      "        self.position = (0, 0, 0)\n",
      "        self.battery_level = 100\n",
      "        self.gps_status = False\n",
      "        self.camera_path = \"drone.mp4\"\n",
      "        self.recording_status = False\n",
      "\n",
      "    def get_drone_position(self):\n",
      "        return self.position\n",
      "\n",
      "    def detect_object(self, object_type):\n",
      "        pass\n",
      "\n",
      "    def get_battery_status(self):\n",
      "        return self.battery_level\n",
      "\n",
      "    def takeoff(self):\n",
      "        print(\"Drone is taking off...\")\n",
      "        # Add code to command the drone to take off\n",
      "        self.battery_level -= 20\n",
      "        self.gps_status = True\n",
      "\n",
      "    def land(self):\n",
      "        print(\"Drone is landing...\")\n",
      "        # Add code to command the drone to safely land\n",
      "\n",
      "    def fly_to(self, destination):\n",
      "        print(\"Drone is flying to\", destination)\n",
      "        # Add code to command the drone to fly to the specified destination\n",
      "\n",
      "    def hover(self, duration):\n",
      "        print(\"Drone is hovering for\", duration)\n",
      "        # Add code to hold the drone at its current position for the specified duration\n",
      "\n",
      "    def start_recording(self):\n",
      "        print(\"Start recording...\")\n",
      "        # Add code to begin video recording with onboard camera\n",
      "\n",
      "    def stop_recording(self):\n",
      "        print(\"Stop recording...\")\n",
      "        # Add code to stop video recording\n",
      "\n",
      "    def capture_image(self):\n",
      "        print(\"Capture image...\")\n",
      "        # Add code to capture a high-resolution image at the current location\n",
      "\n",
      "    def check_gps_signal(self):\n",
      "        print(\"Check GPS signal...\")\n",
      "        # Add code to check the current GPS signal strength and status\n",
      "\n",
      "    def emergency_stop(self):\n",
      "        print(\"Emergency stop...\")\n",
      "        # Add code to immediately stop all drone movements and hover in place\n",
      "\n",
      "# Create an instance of the Drone class\n",
      "drone = Drone()\n",
      "\n",
      "# Call the function to check the battery status before taking off\n",
      "print(drone.get_drone_position())\n",
      "print(drone.get_battery_status())\n",
      "\n",
      "# Command the drone to take off\n",
      "drone.takeoff()\n",
      "print(\"Drone is taking off...\")\n",
      "time.sleep(5)  # Wait for 5 seconds before checking the battery level again\n",
      "print(drone.get_battery_status())\n",
      "\n",
      "# Command the drone to land after taking off\n",
      "drone.land()\n",
      "print(\"Drone is landing...\")\n",
      "time.sleep(5)  # Wait for 5 seconds before checking the battery level again\n",
      "print(drone.get_battery_status())\n",
      "\n",
      "# Command the drone to fly to a specific destination after landing\n",
      "drone.fly_to((50, 50, 50))\n",
      "print(\"Drone is flying to\", drone.get_drone_position())\n",
      "time.sleep(5)  # Wait for 5 seconds before checking the battery level again\n",
      "print(drone.get_battery_status())\n",
      "\n",
      "# Command the drone to hover for a specified duration after flying to the destination\n",
      "drone.hover(30)\n",
      "print(\"Drone is hovering for\", drone.get_battery_status())\n",
      "time.sleep(5)  # Wait for 5 seconds before checking the battery level again\n",
      "print(drone.get_battery_status())\n",
      "\n",
      "# Begin video recording with onboard camera\n",
      "drone.start_recording()\n",
      "print(\"Start recording...\")\n",
      "time.sleep(5)  # Wait for 5 seconds before stopping recording\n",
      "print(drone.get_drone_position())\n",
      "time.sleep(5)  # Wait for 5 seconds before stopping recording again\n",
      "print(drone.stop_recording())\n",
      "\n",
      "# Stop recording after recording for a while\n",
      "drone.capture_image()\n",
      "print(\"Stop recording...\")\n",
      "time.sleep(5)  # Wait for 5 seconds before stopping recording again\n",
      "print(drone.get_drone_position())\n",
      "```\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Enter answer:  exit\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Executing Code: **\"exit\" 是一个英文单词，意为“离开”或“出口”，在多种语境下使用，如从某个地点或场合退出。它通常与交通工具、场所或事件相关联，表示某人或某物离开该地点**。以下是关于exit的相关介绍：\n",
      "\n",
      "1. **交通出行的出口**：在地铁系统中，exit是地铁站点的一个组成部分，乘客通过特定的出口离开车站，前往不同的目的地。\n",
      "\n",
      "2. **商业活动的入口和出口**：EXIT代表一家位于香港的潮流概念店，自开业以来不断开设Pop-Up Store，成为街头文化的标志。店铺采用模块化设计，以适应不同城市人群的文化需求和个性表达。\n",
      "\n",
      "3. **艺术展览的空间设计**：EXI.T北京三里屯太古里店采用了复古木质调与现代金属元素相结合的设计，创造了一个多功能且雅致的环境，为城市居民提供了一个多元文化的展示空间。\n",
      "\n",
      "4. **音乐演出的场地选择**：FUTURA x MODERNICA椅等艺术品和专业级BOSE音响设备共同营造了一个既内敛又先锋的氛围，使得观众在享受音乐的同时，也能体验到一种独特的艺术氛围。这种设计不仅满足了音乐爱好者的需求，也成为了音乐演出场地的一种新趋势。\n",
      "\n",
      "5. **时尚品牌的设计理念**：EXI.T概念店铺在北京的三里屯太古里店使用了模块化设计，旨在承载城市的多元文化和丰富人格。店内采用了复古木质调和现代金属元素，以及FUTURA x MODERNICA椅等艺术作品，创造出一个既雅致又先锋的空间。\n",
      "\n",
      "综上所述，exit作为英文词汇，在不同的领域和语境中有着广泛的含义和使用方式。无论是在交通出行、商业活动还是艺术展览中，exit都扮演着关键的角色，代表着从一个状态到另一个状态的转变。\n",
      "Exiting the Drone Simulator. Goodbye!\n"
     ]
    }
   ],
   "source": [
    "def main():\n",
    "    while True:\n",
    "        user_input = input(\"Enter answer: \")\n",
    "        \n",
    "        answer = ask_spark_ai(user_input)\n",
    "\n",
    "        # 检查生成的代码是否为空或包含明显的错误\n",
    "        if not answer:\n",
    "            print(\"Invalid generated code, please try again with a different command.\")\n",
    "            continue\n",
    "\n",
    "        print(f\"Executing Code: {answer}\")\n",
    "\n",
    "        # 退出条件\n",
    "        if user_input.lower() in [\"exit\", \"quit\"]:\n",
    "            print(\"Exiting the Drone Simulator. Goodbye!\")\n",
    "            break\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n",
    "    #我现在想模拟无人机的操作，请帮我以下面我所声明的函数和后面的说明，实现一下它们，然后调用你所实现的方法，对无人机进行操作无人机起飞前，检查一下电池的状态，然后起飞，向上飞10，向左飞20，然后检查一下gps的状态，最后进行着陆："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "c7062dd9-7563-4d61-b1d0-8984a4c6e4ef",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(0, 0, 0)\n",
      "100\n",
      "Drone is taking off...\n",
      "Drone is taking off...\n",
      "80\n",
      "Drone is landing...\n",
      "Drone is landing...\n",
      "80\n",
      "Drone is flying to (50, 50, 50)\n",
      "Drone is flying to (0, 0, 0)\n",
      "80\n",
      "Drone is hovering for 30\n",
      "Drone is hovering for 80\n",
      "80\n",
      "Start recording...\n",
      "Start recording...\n",
      "(0, 0, 0)\n",
      "Stop recording...\n",
      "None\n",
      "Capture image...\n",
      "Stop recording...\n",
      "(0, 0, 0)\n"
     ]
    }
   ],
   "source": [
    "import time\n",
    "\n",
    "class Drone:\n",
    "    def __init__(self):\n",
    "        self.position = (0, 0, 0)\n",
    "        self.battery_level = 100\n",
    "        self.gps_status = False\n",
    "        self.camera_path = \"drone.mp4\"\n",
    "        self.recording_status = False\n",
    "\n",
    "    def get_drone_position(self):\n",
    "        return self.position\n",
    "\n",
    "    def detect_object(self, object_type):\n",
    "        pass\n",
    "\n",
    "    def get_battery_status(self):\n",
    "        return self.battery_level\n",
    "\n",
    "    def takeoff(self):\n",
    "        print(\"Drone is taking off...\")\n",
    "        # Add code to command the drone to take off\n",
    "        self.battery_level -= 20\n",
    "        self.gps_status = True\n",
    "\n",
    "    def land(self):\n",
    "        print(\"Drone is landing...\")\n",
    "        # Add code to command the drone to safely land\n",
    "\n",
    "    def fly_to(self, destination):\n",
    "        print(\"Drone is flying to\", destination)\n",
    "        # Add code to command the drone to fly to the specified destination\n",
    "\n",
    "    def hover(self, duration):\n",
    "        print(\"Drone is hovering for\", duration)\n",
    "        # Add code to hold the drone at its current position for the specified duration\n",
    "\n",
    "    def start_recording(self):\n",
    "        print(\"Start recording...\")\n",
    "        # Add code to begin video recording with onboard camera\n",
    "\n",
    "    def stop_recording(self):\n",
    "        print(\"Stop recording...\")\n",
    "        # Add code to stop video recording\n",
    "\n",
    "    def capture_image(self):\n",
    "        print(\"Capture image...\")\n",
    "        # Add code to capture a high-resolution image at the current location\n",
    "\n",
    "    def check_gps_signal(self):\n",
    "        print(\"Check GPS signal...\")\n",
    "        # Add code to check the current GPS signal strength and status\n",
    "\n",
    "    def emergency_stop(self):\n",
    "        print(\"Emergency stop...\")\n",
    "        # Add code to immediately stop all drone movements and hover in place\n",
    "\n",
    "# Create an instance of the Drone class\n",
    "drone = Drone()\n",
    "\n",
    "# Call the function to check the battery status before taking off\n",
    "print(drone.get_drone_position())\n",
    "print(drone.get_battery_status())\n",
    "\n",
    "# Command the drone to take off\n",
    "drone.takeoff()\n",
    "print(\"Drone is taking off...\")\n",
    "time.sleep(5)  # Wait for 5 seconds before checking the battery level again\n",
    "print(drone.get_battery_status())\n",
    "\n",
    "# Command the drone to land after taking off\n",
    "drone.land()\n",
    "print(\"Drone is landing...\")\n",
    "time.sleep(5)  # Wait for 5 seconds before checking the battery level again\n",
    "print(drone.get_battery_status())\n",
    "\n",
    "# Command the drone to fly to a specific destination after landing\n",
    "drone.fly_to((50, 50, 50))\n",
    "print(\"Drone is flying to\", drone.get_drone_position())\n",
    "time.sleep(5)  # Wait for 5 seconds before checking the battery level again\n",
    "print(drone.get_battery_status())\n",
    "\n",
    "# Command the drone to hover for a specified duration after flying to the destination\n",
    "drone.hover(30)\n",
    "print(\"Drone is hovering for\", drone.get_battery_status())\n",
    "time.sleep(5)  # Wait for 5 seconds before checking the battery level again\n",
    "print(drone.get_battery_status())\n",
    "\n",
    "# Begin video recording with onboard camera\n",
    "drone.start_recording()\n",
    "print(\"Start recording...\")\n",
    "time.sleep(5)  # Wait for 5 seconds before stopping recording\n",
    "print(drone.get_drone_position())\n",
    "time.sleep(5)  # Wait for 5 seconds before stopping recording again\n",
    "print(drone.stop_recording())\n",
    "\n",
    "# Stop recording after recording for a while\n",
    "drone.capture_image()\n",
    "print(\"Stop recording...\")\n",
    "time.sleep(5)  # Wait for 5 seconds before stopping recording again\n",
    "print(drone.get_drone_position())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "66bf4654-3855-4a36-b8d2-51a6c9b5cec4",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
